import { isNumber } from './is';

// 随机数
export const randomNum = (min=0, max=10000) => {
  return parseInt(Math.random()*(max - min) + min+'');
}
/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
  const keysArr1 = Object.keys(obj1)
  const keysArr2 = Object.keys(obj2)
  if (keysArr1.length !== keysArr2.length) return false
  else if (keysArr1.length === 0 && keysArr2.length === 0) return true
  /* eslint-disable-next-line */ else
    return !keysArr1.some((key) => obj1[key] != obj2[key])
}
/**
 * 随机生成字符串
 * @param length 字符串的长度
 * @param chats 可选字符串区间（只会生成传入的字符串中的字符）
 * @return string 生成的字符串
 */
 export function randomString(length, chats?) {
  if (!length) length = 1
  if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm'
  let str = ''
  for (let i = 0; i < length; i++) {
    const num = randomNum(0, chats.length - 1)
    str += chats[num]
  }
  return str
}
// 随机颜色
export const randomColor = (min=0, max=255) => {
  const r = randomNum(min, max)
  const g = randomNum(min, max)
  const b = randomNum(min, max)
  return `rgb(${r},${g},${b})`
}
// 获取url参数
export const getUrlParams = function ():Record<string,any>{
  var args = {};
  var query = location.search.substring(1);
  var pairs = query.split("&");
  for(var i = 0;i < pairs.length; i++){
      var pos = pairs[i].indexOf("=");
      if(pos == -1) continue;
      var name = pairs[i].substring(0, pos);
      var value = pairs[i].substring(pos + 1);
      value = decodeURIComponent(value);
      args[name] = value;
  }
  return args;
}
/**
 * @description  tree转 list
 */
export const treeTransObject = function(tree, option?):Record<string,any>{
  let {id='id',pid='parentId',children='children',rootPid = ''} = option || {};
  let cloneData = JSON.parse(JSON.stringify(tree))
  var echoObj = {};
  function spread(tree,_pid) {
    for (var i=0; i < tree.length; i++ ) {
      let item = tree[i]
      item[pid] = _pid;
      echoObj[item[id]] = item;
      if(item[children]){
        spread(item[children],item[id])
        delete item.children
      }
    }
  }
  spread(cloneData,rootPid);
  return echoObj;
}

/**
 * @description  list 转 tree
 */
export const arrayTransTree = function(data:Array<any>,option?):Array<any>{
  let {id='id',pid='parentId',children='children',rootPid = ''} = option || {}
  let cloneData = JSON.parse(JSON.stringify(data))
  return cloneData.filter(parent=>{
    let branchArr = cloneData.filter(child => parent[id] == child[pid]);
    branchArr.length>0 ? parent[children] = branchArr : '';
    return parent[pid] === rootPid;
  })
}
/**
 * @description 防抖函数
 */
export const debounce = function (func, wait=50) {
  let timer;
  let echo:Function = function(...result:any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.call(echo.prototype.target,...result)
    }, wait)
  };
  echo.prototype.target = window;
  echo.bind = function(target){
    echo.prototype.target = target;
    return echo;
  }
  return echo
}
export const throttle = function(delay, callback) {
  let timeoutID;
  let lastExec = 0;
  function wrapper() {
    const elapsed = Number(new Date()) - lastExec;
    const args = arguments;
    function exec() {
      lastExec = Number(new Date());
      callback(args);
    }
    clearTimeout(timeoutID);
    if (elapsed > delay) {
      exec();
    } else {
      timeoutID = setTimeout(exec, delay - elapsed);
    }
  }
  return wrapper;
};
/**
 * 时间格式化 默认当前时间
 * @param dateTime 时间戳
 * @param fmt 时间格式
 * @returns {*|string}
 */
export function formatterDateValue(dateTime?, fmt?) {
  let value = fmt ? fmt : "yyyy-MM-dd HH:mm:ss";
  const time = dateTime ? new Date(dateTime) : new Date();
  const timeMap = {
    "M+": time.getMonth() + 1, //月份
    "d+": time.getDate(), //日
    "H+": time.getHours(), //小时
    "m+": time.getMinutes(), //分
    "s+": time.getSeconds(), //秒
    "q+": Math.floor((time.getMonth() + 3) / 3), //季度
    S: time.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(value)) {
    value = value.replace(
      RegExp.$1,
      (time.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (const key in timeMap) {
    if (new RegExp("(" + key + ")").test(value)) {
      value = value.replace(
        RegExp.$1,
        RegExp.$1.length == 1
          ? timeMap[key]
          : ("00" + timeMap[key]).substr(("" + timeMap[key]).length)
      );
    }
  }
  return value;
}